package com.lwt.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lwt.yygh.cmn.listener.DictListencer;
import com.lwt.yygh.cmn.mapper.DictMapper;
import com.lwt.yygh.cmn.service.DictService;
import com.lwt.yygh.model.cmn.Dict;
import com.lwt.yygh.model.cmn.DictEeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author Weton Li
 * @Date 2021/4/13 17:38
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    /**
     * 根据id查询孩子数据
     *
     * @param id
     * @return
     */
    @Override
    @Cacheable(value = "dict",keyGenerator = "keyGenerator") // 先查缓存
    public List<Dict> findChildData(Long id) {

        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id); // 将数据库中的id，和参数id对比
        List<Dict> list = baseMapper.selectList(wrapper);


        for (Dict dict : list) {
            Long dictId = dict.getId(); // 此id非彼参数id
            boolean isHave = isChild(dictId); // 调用isChild()方法
            dict.setHasChildren(isHave);
        }
        return list;
    }

    /**
     * 导出数据到磁盘，即下载
     *
     * @param resp
     */
    @Override
    public void exportDictData(HttpServletResponse resp) {
        resp.setContentType("application/vnd.ms-excel");
        resp.setCharacterEncoding("utf-8");
        String fileName = "dict";
        resp.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
// 查询数据库
        List<Dict> list = baseMapper.selectList(null);
        // 将Dict转换为DictEeVo
        ArrayList<DictEeVo> dictEeVoList = new ArrayList<>();
        for (Dict dict : list) {
            DictEeVo dictEeVo = new DictEeVo();
            BeanUtils.copyProperties(dict, dictEeVo);
            dictEeVoList.add(dictEeVo);
        }

        try {
            EasyExcel.write(resp.getOutputStream(), DictEeVo.class)
                    .sheet("dict")
                    .doWrite(dictEeVoList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 需要监听器 去上传导入 往内存写数据
     * @param file
     */
    @Override
    @CacheEvict(value = "dict",allEntries = true) // 添加时清空缓存
    public void importDictData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),DictEeVo.class,new DictListencer(baseMapper))
            .sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断是否有孩子节点数据
     *
     * @param id
     * @return
     */
    private boolean isChild(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        Integer count = baseMapper.selectCount(wrapper);
        return count > 0;
    }

    @Override
    public String getDictName(String dictCode, String value) {
        if (StringUtils.isEmpty(dictCode)) { // 如果dictCode为空，则只通过value查询
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("value", value);
            Dict dict = baseMapper.selectOne(wrapper);
            return dict.getName();
        }else { // 如果dictCode不为空，可能会出现value有相同值的情况

            /*
            总结，一个对象，通过一个属性值查询出一条bean对象，再通过这条bean对象获取另一属性值
            可解决：某些情况下，不同bean对象有属性值重复的问题
             */
            Dict dictByDictCode = this.getDictByDictCode(dictCode);// 根据dictcode查询dict对象的id值，再通过parent_id
            Long id = dictByDictCode.getId();
            Dict finalDict = baseMapper.selectOne(new QueryWrapper<Dict>()
                    .eq("parent_id", id) // 医院等级id为10000，查找parent_id列值等于10000（id）的数据
                    .eq("value", value));
            return finalDict.getName();
        }
    }
    // 根据dictcode查询dict对象的id值，再通过parent_id
    private Dict getDictByDictCode(String dictCode){
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code", dictCode);
        Dict codeDict = baseMapper.selectOne(wrapper);
        return codeDict;
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        // 根据dictCode获取对应id
        Dict dict = this.getDictByDictCode(dictCode);
        // 根据id获取子节点
        List<Dict> childData = this.findChildData(dict.getId());
        return childData;
    }

}
